const express = require('express');
const uuid = require('node-uuid');
const { Message,MessageList } = require('../utils/message');
const vipModel = require('../models/vip');

const router = express.Router();

router.post('/',(req,res,next)=>{
  const {name,price,discount}=req.body;
  const id=uuid.v1();
  const vip=new vipModel({id,name,price,discount});
  vip.save().then(data=>{
    if(data){
      res.json(Message(200,'添加成功！'));
    }
  });
});

router.delete('/',(req,res,next)=>{
  const {id}=req.query;
  if(id){
    vipModel.deleteOne({id}).then(data=>{
      if(data.deletedCount!==0){
        res.json(Message(200,'删除成功！'))
      }else{
        res.json(Message(400,'删除失败'))
      }
    })
  }else{
    res.json(Message(400,'缺少参数id'))
  }
})

router.put('/',(req,res,next)=>{
  const {id}=req.query;
  const {price,discount}=req.body;
  if(id){
    vipModel.updateOne({id},{price,discount}).then(data=>{
      console.log(data)
      if(data.acknowledged&&data.modifiedCount!==0){
        res.json(Message(200,'修改成功！'));
      }else{
        res.json(Message(400,'修改失败！'));
      }
    })
  }else{
    res.json(Message(400,'缺少参数id'));
  }
})

router.get('/',(req,res,next)=>{
  const {id,vipType}=req.query;
  if(id){
    vipModel.findOne({id}).then(data=>{
      res.json(Message(200,'',data))
    })
    return 
  }
  if(vipType){
    vipModel.findOne({vipType}).then(data=>{
      res.json(Message(200,'',data))
    })
    return 
  }
  vipModel.find().then(data=>{
    res.json(MessageList(200,'',data,0,0,data.length))
  })
})
module.exports = router